package cn.kgc.controller;

import cn.kgc.entity.Clazz;
import cn.kgc.service.ClazzService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author mosin
 * date 2022/1/16
 * @version 1.0
 */
@RestController
@RequestMapping("/clazzs")
public class ClazzController {
    @Autowired
    private ClazzService clazzService;
    @Value("${upload}")
    private  String filePath;
    @GetMapping
    public List<Clazz> getAll(){
        List<Clazz> clazzes = clazzService.queryAll();
        return  clazzes;
    }


    //添加班级信息
    @PostMapping
    public Clazz addClazz(String name, MultipartFile logo ,String tagId){

        System.out.println(name);
        System.out.println(logo.getOriginalFilename());
        System.out.println(tagId);

        //处理文件上传的名字
        String newFileName = UUID.randomUUID().toString().replace("-", "")+"."+
                FilenameUtils.getExtension(logo.getOriginalFilename());
        //文件上传处理
        try {
            logo.transferTo(new File(filePath, newFileName));
            //创建clazz对象 封装数据 持久化到数据库
            Clazz clazz = new Clazz();
            clazz.setTagId(tagId);
            clazz.setName(name);
            clazz.setPath(newFileName);

            return clazzService.addClazz(clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }


    //删除班级信息
    @DeleteMapping("/{id}")
    public void delClazz(@PathVariable Integer id){
        clazzService.delById(id);
    }

    //根据id 查询班级信息
    @GetMapping("/{id}")
    public Clazz getClazz(@PathVariable Integer id){
        Clazz clazz = clazzService.getOne(id);
        return clazz;
    }

}
